// Updating a text-file by using a temporary file
import java.io.*;
import java.util.Scanner;
public class UpdateQuizScores{
   public static void main(String[] args)throws IOException{

       Scanner kbdScanner = new Scanner(System.in);
       File infile = new File("scores.txt");    //1. connect an existing input file to a scanner
       Scanner sc = new Scanner(infile);        //

       File outfile = new File("temp.txt");  // 2. create a new output file
       outfile.createNewFile();                 //

       PrintWriter pwriter = new PrintWriter(outfile); //3. wrap the output stream to a PrintWriter

       final int numQuizzes = 5;
       double score,grades[] = new double[numQuizzes];
       int id, inputID, quizNum;
       System.out.printf("Enter the ID#: ");
       inputID = kbdScanner.nextInt();
       System.out.printf("Enter the Quiz number of the quiz to be modified [1 - 5]: ");
       quizNum = kbdScanner.nextInt();
       System.out.printf("Enter the new quiz score for quiz#%d: ", quizNum);
       score = kbdScanner.nextDouble();
       boolean found = false;
       while(sc.hasNextInt()){
            id = sc.nextInt();
            if(id == inputID){
                 found = true;
                 for(int k = 0; k <= numQuizzes - 1; k++)   // Store the grades of the student in an array
                    grades[k] = sc.nextDouble();            //

                 grades[quizNum - 1] = score;               // modify the required quiz score

                 pwriter.printf("%-15d", id);
                 for(int k = 0; k <= numQuizzes - 1; k++)
                    pwriter.printf("%6.1f", grades[k]);   // update the output file
                 pwriter.printf("%n");
            }else{
               pwriter.printf("%-15d", id);                  // write the grades of other students without change
               for(int k = 0; k <= numQuizzes - 1; k++){     //
                   pwriter.printf("%6.1f", sc.nextDouble());  //
               }

               pwriter.printf("%n");
            }
       }

       if(! found)
         System.out.println("Error: ID not found.");
       else
         System.out.println("Input file scores.txt modified . . .");

       pwriter.close();                    // 7. close the writer and the scanner
       sc.close();                         //
       infile.delete();                    // 8. delete the input file
       outfile.renameTo(infile);           // 9. rename the output file as the input file
   }
}